package cn.kaguyaever.web;

import cn.kaguyaever.entity.User;
import cn.kaguyaever.utils.MailText;
import cn.kaguyaever.utils.MailUtil;
import cn.kaguyaever.utils.RandomUtil;
import com.google.gson.Gson;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet("/emailServlet")
public class EmailServlet extends BaseServlet {

    protected void wordVerification(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        String code = req.getParameter("code");
        boolean flag = false;
        if (token != null && token.equalsIgnoreCase(code)) {
            flag = true;
        }
        Gson gson = new Gson();
        String wordVerification = gson.toJson(flag);
        resp.getWriter().write(wordVerification);
    }

    protected void sendEmail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            User user = (User) req.getSession().getAttribute("user");//获得登陆用户信息
            String email = user.getEmail();
            String username = user.getUsername();
            MailUtil.receiveMailAccount = email;

            //创建参数配置
            Properties props = new Properties();

            // 发送服务器需要身份验证
            props.setProperty("mail.smtp.auth", "true");
            // 设置服务器的主机名
            props.setProperty("mail.host", MailUtil.emailSMTPHost);
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.ssl.enable", "true");

            // 根据配置创建Session
            Session session = Session.getInstance(props);
            session.setDebug(true);
            // 创建一封邮件
            String code = RandomUtil.getRandom();
            String html = MailText.mail(code, username);
            MimeMessage message = MailUtil.creatMimeMessage(session, MailUtil.emailAccount,
                    MailUtil.receiveMailAccount, html, username);
            // 根据Session获取邮件传输对象
            Transport transport = session.getTransport();

            transport.connect(MailUtil.emailAccount, MailUtil.emailPassword);
            // 发送邮件
            transport.sendMessage(message, message.getAllRecipients());
            // 关闭连接
            transport.close();
            // 将验证码和创建时间写入Session
            req.getSession().setAttribute("code", code);
            req.getSession().setAttribute("createTime", System.currentTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("msg", "邮件发送失败");
        }
    }

    protected void emailVerification(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sessionCode = (String) req.getSession().getAttribute("code");
        Long createTime = (Long) req.getSession().getAttribute("createTime");
        if (sessionCode != null) {//用户还未获取验证码
            if (System.currentTimeMillis() - createTime > 1000 * 60 * 5) {//验证码在5分钟后失效
                req.getSession().setAttribute("msg", "邮箱验证码已失效！");
                req.getSession().removeAttribute("code");
                req.getSession().removeAttribute("createTime");
                resp.sendRedirect("user/mail_verification.jsp");
            } else {
                String emailCode = req.getParameter("emailCode");
                if (sessionCode.equalsIgnoreCase(emailCode)) {//对比用户输入和Session中的验证码
                    req.setAttribute("msg", "验证成功请修改密码！");
                    req.getSession().setAttribute("verification",true);
                    req.getSession().removeAttribute("msg");
                    req.getRequestDispatcher("user/change_password.jsp").forward(req,resp);
                } else {
                    req.getSession().setAttribute("msg", "邮箱验证码错误！");
                    resp.sendRedirect("user/mail_verification.jsp");
                }
            }
        } else {
            req.getSession().setAttribute("msg", "请先获取邮箱验证码！");
            resp.sendRedirect("user/mail_verification.jsp");
        }
    }
}
